import Vue from 'vue'
import Router from 'vue-router'
// 导入vuex仓库对象
import store from '@/store'
import { getToken } from '@/utils/auth'

// 引入动态路由表
import { asyncRoutes } from '@/router/dynamicRoute'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

//静态路由
export const staticRoutes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/workbench'
  },
  {
    path: '/workbench',
    component: Layout,
    children: [{
      path: '',
      component: () => import('@/views/Workbench/index'),
      meta: { title: '工作台', icon: 'el-icon-data-board' }
    }]
  },
  // {
  //   path: '/park',
  //   component: Layout,
  //   permission: 'park',
  //   meta: { title: '园区管理', icon: 'el-icon-office-building' },
  //   children: [{
  //     path: 'building',
  //     permission: 'park:building',
  //     meta: { title: '楼宇管理' },
  //     component: () => import('@/views/Park/Building/index')
  //   },
  //   {
  //     path: 'enterprise',
  //     permission: 'park:enterprise',
  //     meta: { title: '企业管理' },
  //     component: () => import('@/views/Park/Enterprise/index')
  //   }]
  // },
  {// 企业管理添加页面
    path: '/exterpriseAdd',
    component: () => import('@/views/Park/Enterprise/Add')
  },
  {//查看企业详细页面
    path: '/exterpriseDetail',
    component: () => import('@/views/Park/Enterprise/Detail')
  },

  // {//行车管理
  //   path: '/parking',
  //   component: Layout,
  //   permission: 'parking',
  //   meta: { title: '行车管理', icon: 'el-icon-guide' },
  //   children: [{
  //     path: 'area',
  //     permission: 'parking:area',
  //     component: () => import('@/views/Car/CarArea'),
  //     meta: { title: '区域管理' }
  //   }, {
  //     path: 'card',
  //     permission: 'parking:card',
  //     component: () => import('@/views/Car/CarCard'),
  //     meta: { title: '月卡管理' }
  //   }, {
  //     path: 'pay',
  //     permission: 'parking:payment',
  //     component: () => import('@/views/Car/CarPay'),
  //     meta: { title: '停车缴费管理' }
  //   },
  //   {
  //     path: 'rule',
  //     permission: 'parking:rule',
  //     component: () => import('@/views/Car/CarRule'),
  //     meta: { title: '计费规则管理' }
  //   }]
  // },
  {// 月卡添加页面
    path: '/cardAdd',
    component: () => import('@/views/Car/CarCard/addCard')
  },
  // {
  //   path: '/pole',
  //   component: Layout,
  //   permission: 'pole',
  //   meta: { title: '一体杆管理', icon: 'el-icon-refrigerator' },
  //   children: [{
  //     path: 'info',
  //     permission: 'pole:info',
  //     component: () => import('@/views/Rod/RodManage'),
  //     meta: { title: '一体杆管理' }
  //   }, {
  //     path: 'waring',
  //     permission: 'pole:warning',
  //     component: () => import('@/views/Rod/RodWarn'),
  //     meta: { title: '告警记录' }
  //   }]
  // },
  // {
  //   path: '/sys',
  //   component: Layout,
  //   permission: 'sys',
  //   meta: { title: '系统管理', icon: 'el-icon-setting' },
  //   children: [{
  //     path: 'role',
  //     permission: 'sys:role',
  //     component: () => import('@/views/System/Role/index'),
  //     meta: { title: '角色管理' }
  //   }, {
  //     path: 'user',
  //     permission: 'sys:user',
  //     component: () => import('@/views/System/Employee/index'),
  //     meta: { title: '员工管理' }
  //   }]
  // },
  {// 角色添加&编辑页面
    path: '/roleAdd',
    component: () => import('@/views/System/Role/AddRole')
  },
  // {// 角色编辑页面
  //   path: '/roleEdit',
  //   component: () => import('@/views/System/Role/EditRole')
  // },
  // {
  //   path: '/404',
  //   component: () => import('@/views/404'),
  //   hidden: true
  // }
]


const createRouter = () => new Router({
  // mode: 'history', // require service support
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: staticRoutes// 配置静态路由规则
})

const router = createRouter()

//利用token控制路由跳转（写在router对象实例创建之后）
// const WHITE_LIST = ['/login', '/404']//路由白名单
// router.beforeEach((to, from, next) => {
//   const token = getToken()
//   if(token){
//     next()
//   }else{
//     if(WHITE_LIST.includes(to.path)){
//       next()
//     }else{
//       next('/login')
//     }
//   }
// })


// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]// 去重
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]// 去重
}

// 根据权限标识过滤路由表
/** * 
 * @param {*} firstRoutePerms ['park','parking',...]
 * @param {*} secondRoutePerms  ['park:building','parking:area',...]
 * @param {*} dinamicRoutes 动态路由规则表
 * @returns 
 */
function getRoutes(firstRoutePerms, secondRoutePerms, dinamicRoutes) {
  // 参数验证
  if (!Array.isArray(firstRoutePerms) || !Array.isArray(secondRoutePerms) || !Array.isArray(dinamicRoutes)) {
    console.error('getRoutes: Invalid parameters', { firstRoutePerms, secondRoutePerms, dinamicRoutes });
    return [];
  }

  try {
    // 1. 根据一级路由对动态路由表做过滤
    return dinamicRoutes.filter(route => {
      return route.permission && firstRoutePerms.includes(route.permission);
    }).map(item => {
      // 2. 对二级路由做过滤
      return {
        ...item,
        children: Array.isArray(item.children)
          ? item.children.filter(child => child.permission && secondRoutePerms.includes(child.permission))
          : []
      };
    });
  } catch (error) {
    console.error('Error in getRoutes:', error);
    return [];
  }
}

//路由守卫
//利用token控制路由跳转（写在router对象实例创建之后）
router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    next();
    return;
  }

  const token = store.state.user.token;
  if (!token) {
    next('/login');
    return;
  }

  try {
    if (!store.state.user.profile.id) {
      const permissions = await store.dispatch('user/getProfile');
      console.log('获取到的权限列表:', permissions);

      if (!Array.isArray(permissions)) {
        console.error('权限格式无效:', permissions);
        next('/login');
        return;
      }

      const firstRoutePerms = getFirstRoutePerms(permissions);
      console.log('一级路由权限:', firstRoutePerms);

      const secondRoutePerms = getSecondRoutePerms(permissions);
      console.log('二级路由权限:', secondRoutePerms);

      console.log('动态路由配置:', asyncRoutes);

      if (permissions.includes('*:*:*')) {
        // 管理员权限
        asyncRoutes.forEach(item => router.addRoute(item));
        // 将动态路由添加到store中
        store.commit('menu/setMenuList', asyncRoutes)
      } else {
        // 普通用户权限
        const filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes);
        filterRoutes.forEach(item => router.addRoute(item));
        // 将动态路由添加到store中
        store.commit('menu/setMenuList', filterRoutes)
      }

      // 添加404路由
      router.addRoute({
        path: '/404',
        component: () => import('@/views/404'),
        hidden: true
      });

      // 重新触发路由导航
      next({ ...to, replace: true });
      return;
    }

    next();
  } catch (error) {
    console.error('路由守卫错误:', error);
    next('/login');
  }
});

// 重置路由方法，在退出登录时调用
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter()
  // 使用新的路由记录覆盖掉老的路由记录
  router.matcher = newRouter.matcher
}


export default router
